//导入数据关联
//导入express模块和MySQL模块
var mysql = require('mysql');
var express = require("express");
//执行experss
var app = express();

//使用bodyParser模块，接收post参数
var bodyParser = require('body-parser');
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());


//设置跨域访问（设置在所有的请求前面即可）
app.all("*", function (req, res, next) {
    //设置允许跨域的域名，*代表允许任意域名跨域
    res.header("Access-Control-Allow-Origin", "*");
    //允许的header类型
    res.header("Access-Control-Allow-Headers", "content-type");
    //跨域允许的请求方式 
    res.header("Access-Control-Allow-Methods", "DELETE,PUT,POST,GET,OPTIONS");
    if (req.method == 'OPTIONS')
        res.send(200); //让options尝试请求快速结束
    else
        next();
});

app.get("/", function (req, res) {
    console.log(req.query)
    //传送HTTP响应
    res.send("端口启动成功")
})

// 所有的图片查询
app.get("/queryAll", function (req, res) {
    // console.log("开始查询所有用户信息")
    //直接去数据库查询所有的数据
    var connection = mysql.createConnection({
        host: 'localhost',
        user: 'root',
        password: '123456',
        port: '3306',
        database: 'app'
    });
    connection.connect();
    //sql语句
    var sql = `select * from tuijian`;
    //执行sql
    connection.query(sql, function (error, result) {
        if (error) {
            console.log("出错了：" + error.message);
            res.send({
                state: false,
                des: "出错了：" + error.message
            })
        }
        else {
            if (result.length == 0) {
                res.send("无任何用户数据！")
            }
            else {
                res.send(result)
            }
        }
        //关闭数据库连接
        connection.end();
    })
})
//仅查询用户名和头像
app.get("/queryAlluser", function (req, res) {
    // console.log("开始查询所有用户信息")
    //直接去数据库查询所有的数据
    var connection = mysql.createConnection({
        host: 'localhost',
        user: 'root',
        password: '123456',
        port: '3306',
        database: 'app'
    });
    connection.connect();
    //sql语句
    var sql = `select * from userdata`;
    //执行sql
    connection.query(sql, function (error, result) {
        if (error) {
            console.log("出错了：" + error.message);
            res.send({
                state: false,
                des: "出错了：" + error.message
            })
        }
        else {
            if (result.length == 0) {
                res.send("无任何用户数据！")
            }
            else {
                res.send(result)
            }
        }
        //关闭数据库连接
        connection.end();
    })
})
//查询图片列表
app.get("/queryAllimg", function (req, res) {
    // console.log("开始查询所有用户信息")
    //直接去数据库查询所有的数据
    var connection = mysql.createConnection({
        host: 'localhost',
        user: 'root',
        password: '123456',
        port: '3306',
        database: 'app'
    });
    connection.connect();
    //sql语句
    var sql = `select * from imgdata`;
    //执行sql
    connection.query(sql, function (error, result) {
        if (error) {
            console.log("出错了：" + error.message);
            res.send({
                state: false,
                des: "出错了：" + error.message
            })
        }
        else {
            if (result.length == 0) {
                res.send("无任何用户数据！")
            }
            else {
                res.send(result)
            }
        }
        //关闭数据库连接
        connection.end();
    })
})
app.post("/queryAllimg", function (req, res) {
    // console.log("开始查询所有用户信息")
    //直接去数据库查询所有的数据
    var connection = mysql.createConnection({
        host: 'localhost',
        user: 'root',
        password: '123456',
        port: '3306',
        database: 'app'
    });
    connection.connect();
    //sql语句
    var sql = `select * from imgdata where id=?`;
    //执行sql
    connection.query(sql,[req.body.id], function (error, result) {
        if (error) {
            console.log("出错了：" + error.message);
            res.send({
                state: false,
                des: "出错了：" + error.message
            })
        }
        else {
            if (result.length == 0) {
                res.send("无任何用户数据！")
            }
            else {
                res.send(result)
            }
        }
        //关闭数据库连接
        connection.end();
    })
})
//查询页面点击后的单独的详情页面,带id参数
app.post("/queryAll", function (req, res) {
    // console.log("开始查询所有用户信息")
    //直接去数据库查询所有的数据
    var connection = mysql.createConnection({
        host: 'localhost',
        user: 'root',
        password: '123456',
        port: '3306',
        database: 'app'
    });
    connection.connect();
    //sql语句
    var sql = `select * from tuijian where id=?`;
    //执行sql
    connection.query(sql, [req.body.id],function (error, result) {
        if (error) {
            console.log("出错了：" + error.message);
            res.send({
                state: false,
                des: "出错了：" + error.message
            })
        }
        else {
            if (result.length == 0) {
                res.send("无任何用户数据！")
            }
            else {
                res.send(result)
            }
        }
        //关闭数据库连接
        connection.end();
    })
})
// 登录验证
// post请求，data里面带name和password参数
app.post("/logindlyz", function (req, res) {
    console.log(req.body.name);
    var connection = mysql.createConnection({
        host: 'localhost',
        user: 'root',
        password: '123456',
        port: '3306',
        database: 'app'
    });
    connection.connect();
    var sql = `select * from users where user=?`;
    connection.query(sql, [req.body.name], function (error, result) {
        // console.log(result)
        if (error) {
            console.log("出错了", error.message);
            res.send("出错了：" + error.message)
            con.end()
            return;
        }
        if (result.length > 0) {
            console.log(result[0].password,req.body.password);
            if (result[0].password == req.body.password) {
                res.send({
                    mes: "登录成功",
                    data: result
                })
            } else {
                res.send({
                    mes: "密码错误",
                    data: result
                })
            }
        }
        else {
            res.send({
                mes: "用户不存在",
                data: result
            })
        }
        connection.end()
    })
})
// 注册
// post请求，注册的时候带name，password，phone参数
app.post("/addUser", function (req, res) {
    var connection = mysql.createConnection({
        host: 'localhost',
        user: 'root',
        password: '123456',
        port: '3306',
        database: 'app'
    });
    connection.connect();
    var sql = `select * from users where user=?`;
    connection.query(sql, [req.body.name], function (error, result) {
        // console.log(result)
        if (error) {
            console.log("出错了", error.message);
            res.send("出错了：" + error.message)
            connection.end()
            return;
        }
        if (result.length > 0) {
            res.send("用户已经存在");
        }
        else {
            sql = "INSERT INTO `users` ( `username`,`user`, `password`,`phone`,`imgurl`) VALUES ( ?,?, ?,?,'https://img0.baidu.com/it/u=4221498374,962514080&fm=26&fmt=auto')";
            connection.query(sql, [req.body.name,req.body.name, req.body.password, req.body.phone], function (error, result) {
                // console.log(result)
                if (error) {
                    console.log("出错了", error.message);
                    res.send("出错了：" + error.message)
                    connection.end()
                    return;
                }
                res.send('注册成功')
            })
        }
        connection.end()
    })
})
//收藏
app.post("/updateSta", function (req, res) {
    var connection = mysql.createConnection({
        host: 'localhost',
        user: 'root',
        password: '123456',
        port: '3306',
        database: 'app'
    });
    connection.connect();
    console.log(req.body.state,req.body.id);
    var sql = `UPDATE tuijian SET state = ? WHERE id = ?`;
    connection.query(sql, [req.body.state, req.body.id], function (error, result) {
        // console.log(result)
        if (error) {
            console.log("出错了", error.message);
            res.send("出错了：" + error.message)
            con.end()
            return;
        }
        res.send('修改成功')
        connection.end()
    })
})
//用户搜索
app.post("/queryData", function (req, res) {
    var connection = mysql.createConnection({
        host: 'localhost',
        user: 'root',
        password: '123456',
        port: '3306',
        database: 'app'
    });
    connection.connect();
    var sql;
    console.log(123);
    if(req.body.zt=='文章'){
        sql = ` select * from tuijian where title like '%${req.body.title}%'`
    }else if(req.body.zt=='用户'){
        sql = `select * from users where username like '%${req.body.title}%'`;
    }
    connection.query(sql, function (error, result) {
        if (error) {
            console.log("出错了", error.message);
            res.send("出错了：" + error.message)
            con.end()
            return;
        }
        if (result.length > 0) {
            res.send({
                mes:"查询成功",
                data:result
            });
        }
        else {
            res.send({
                mes:"未找到",
                data:result
            })
        }
        connection.end()
    })
})

app.listen(8081, function () {
    console.log("后端监听的地址为：http://192.168.219.249:8081")
})